package com.java.common.service.manager.factory;

import java.util.TimerTask;

import com.java.common.lang.enums.UserTypeEnum;
import com.java.module.system.domain.dto.LogininforDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.java.common.constant.Constants;
import com.java.common.utils.ServletUtils;
import com.java.common.utils.StringUtils;
import com.java.common.utils.ip.AddressUtils;
import com.java.common.utils.ip.IpUtils;
import com.java.common.utils.spring.SpringUtils;
import com.java.module.system.domain.SysLogininfor;
import com.java.module.system.domain.SysOperLog;
import com.java.module.system.service.ISysLogininforService;
import com.java.module.system.service.ISysOperLogService;

import eu.bitwalker.useragentutils.UserAgent;

/**
 * 异步工厂（产生任务用）
 *
 * @author Administrator
 */
public class AsyncFactory {

    private static final Logger LOG = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) {
        return recordLogininfor(new LogininforDTO(username, status, message, UserTypeEnum.ADMIN, null), message, args);
    }

    /**
     * 记录登录信息
     *
     * @param body
     * @return 任务task
     */
    public static TimerTask recordLogininfor(LogininforDTO body, final Object... args) {
        String username = body.getUsername();
        String status = body.getStatus();
        String message = body.getMessage();
        Integer userType = body.getUserType().getType();
        String token = StringUtils.defaultString(body.getToken(), "");
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getUserAgent());
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIp(ip);
                StringBuilder s = new StringBuilder();
                s.append(getBlock(ip));
                s.append(address);
                s.append(getBlock(username));
                s.append(getBlock(status));
                s.append(getBlock(message));
                // 打印信息到日志
                LOG.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                logininfor.setUserType(userType);
                logininfor.setToken(token);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor, status);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIp(operLog.getOperIp()));
                SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
            }
        };
    }

    public static String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return StringUtils.format("[{}]", msg.toString());
    }

}